﻿using System;
using System.Collections.Generic;
using System.Text;
using T.ServiceComponent.DAC.Service;
using T.FAS.Runtime.Base.Entity;
using System.Data;
using T.ServiceComponent.DataAccessEx.Core;
using System.Transactions;
using System.Linq;

namespace T.FAS.Runtime.Base.Dao
{
    public class FunctionTreeDao : DaoService<Function>
    {
        public FunctionTreeDao(string dbName = "TFAS")
        {
            DBName = dbName;
        }
        /// <summary>
        /// 获取产品版本、子系统下的关键应用
        /// </summary>
        /// <param name="productVersionID"></param>
        /// <param name="subSystemID"></param>
        /// <returns></returns>
        public List<Function> GetApplications(string productVersionID, string subSystemID)
        {
            List<Function> apps = new List<Function>();
            string sql = "SELECT MenuID ID,Code,FULLNAME Name,APPLICATIONID APPID,ProductVersionID PARENTID,ProductVersionID,ProductSubSystemID FROM SYS_SYSMENU M WHERE DeleteMark = 0 AND IsDetail=0 and ParentID = '0' and ProductVersionID=@productVersionID";
            if (!string.IsNullOrEmpty(subSystemID))
            {
                sql += " and ProductSubSystemID =@subSystemID";
            }
            sql += " order by Code";
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            paramsList.Add(this.DB.MakeInParam("@productVersionID", TDbDataType.VarChar, productVersionID));
            paramsList.Add(this.DB.MakeInParam("@subSystemID", TDbDataType.VarChar, subSystemID));
            DataSet ds = DB.ExecuteDataSet(sql, paramsList.ToArray());
            if (ds.Tables.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    var func = ConvertToFunction(dr);
                    apps.Add(func);
                }
            }
            return apps;
        }
        
        public List<Function> GetModules(Function app)
        {
            List<Function> apps = new List<Function>();
            string sql = "SELECT MenuID ID,Code,FULLNAME Name,APPLICATIONID APPID,Layer,PARENTID,ProductVersionID,ProductSubSystemID FROM SYS_SYSMENU M where ProductVersionID=@productVersionID And ApplicationID = @applicationID and ProductSubSystemID = @subSystemID AND M.DeleteMark = 0 AND M.IsDetail=0 and Layer is not null order by Code";
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            paramsList.Add(this.DB.MakeInParam("@productVersionID", TDbDataType.VarChar, app.ProductVersionID));
            paramsList.Add(this.DB.MakeInParam("@applicationID", TDbDataType.VarChar, app.ApplicationID));
            paramsList.Add(this.DB.MakeInParam("@subSystemID", TDbDataType.VarChar, app.SubSystemID));
            DataSet ds = DB.ExecuteDataSet(sql, paramsList.ToArray());
            if (ds.Tables.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    var func = ConvertToFunction(dr);
                    func.ModuleID = func.ID;
                    apps.Add(func);
                }
            }
            return apps;
        }
        public List<Function> GetMenuGroup(Function module)
        {
            List<Function> groups = new List<Function>();
            List<Function> topGroups = new List<Function>();
            string sql = "SELECT GROUPID ID,Code,GROUPNAME NAME,APPLICATIONID APPID,ParentID,ProductVersionID,ProductSubSystemID FROM SYS_MENUGROUP where ProductVersionID=@productVersionID And MenuID =@MenuID and ProductSubSystemID = @subSystemID order by Code";
            List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
            paramsList.Add(this.DB.MakeInParam("@productVersionID", TDbDataType.VarChar, module.ProductVersionID));
            paramsList.Add(this.DB.MakeInParam("@MenuID", TDbDataType.VarChar, module.ID));
            paramsList.Add(this.DB.MakeInParam("@subSystemID", TDbDataType.VarChar, module.SubSystemID));
            DataSet ds = DB.ExecuteDataSet(sql, paramsList.ToArray());
            if (ds.Tables.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    var func = ConvertToFunction(dr);
                    func.ModuleID = module.ID;
                    if (func.ParentID == "0")
                    {
                        func.ParentID = module.ID;
                        topGroups.Add(func);
                    }
                    else
                    {
                        groups.Add(func);
                    }
                }
            }
            foreach (var topGroup in topGroups)
            {
                SetNodes(topGroup, groups);
            }
            return topGroups;
        }
        /// <summary>
        /// 获取功能组名称
        /// </summary>
        /// <param name="groupID"></param>
        public string GetGroupName(string groupID, string productVersionID)
        {
            using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
            {
                string sql = "select GROUPNAME from SYS_MENUGROUP where GROUPID=@groupId and productVersionID=@productVersionID";
                List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
                paramsList.Add(this.DB.MakeInParam("@groupID", TDbDataType.VarChar, groupID));
                paramsList.Add(this.DB.MakeInParam("@productVersionID", TDbDataType.VarChar, productVersionID));
                object obj = DB.ExecuteScalar(sql, paramsList.ToArray());
                if (obj == null || obj == DBNull.Value)
                {
                    return null;
                }
                else
                {
                    return Convert.ToString(obj);
                }
            }
        }
        /// <summary>
        /// 获取关键应用缩写
        /// </summary>
        /// <param name="applicationId">关键应用的ApplicationId</param>
        /// <returns>缩写，SYS_APPLICATION表中的AppID字段</returns>
        public string GetApplicationSortName(string applicationId,string subSystemID)
        {
            using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
            {
                string sql = "select AppID,ProductSubsystemId from SYS_APPLICATION where APPLICATIONID=@appId";
                List<IDbDataParameter> paramsList = new List<IDbDataParameter>();
                paramsList.Add(this.DB.MakeInParam("@appId", TDbDataType.VarChar, applicationId));
                paramsList.Add(this.DB.MakeInParam("@subSystemID", TDbDataType.VarChar, subSystemID));
                DataSet ds = DB.ExecuteDataSet(sql, paramsList.ToArray());
                List<Function> functions = new List<Function>();
                if (ds.Tables.Count > 0)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        var func = new Function();
                        func.ApplicationID = Convert.ToString(dr["AppID"]);
                        func.ParentID = Convert.ToString(dr["ProductSubsystemId"]);
                        functions.Add(func);
                    }
                    var app = functions.FirstOrDefault(t => t.ParentID == subSystemID);
                    if (app != null)
                        return app.ApplicationID;
                    else
                        return functions[0].ApplicationID;
                }
                return null;
            }

        }
        /// <summary>
        /// 递归设置子节点
        /// </summary>
        /// <param name="node"></param>
        /// <param name="allNodes"></param>
        public void SetNodes(Function node, List<Function> allNodes)
        {
            List<Function> nodes = allNodes.FindAll(F => F.ParentID == node.ID);
            if (nodes != null && nodes.Count > 0)
            {
                node.Nodes = nodes;
                foreach (var n in node.Nodes)
                {
                    n.ModuleID = node.ModuleID;
                    SetNodes(n, allNodes);
                }
            }
        }


        private static Function ConvertToFunction(DataRow dr)
        {
            Function function = new Function();
            function.ID = Convert.ToString(dr["ID"]);
            function.Code = Convert.ToString(dr["Code"]);
            function.Name = Convert.ToString(dr["Name"]);
            function.ApplicationID = Convert.ToString(dr["APPID"]);
            function.ParentID = Convert.ToString(dr["PARENTID"]);
            function.ProductVersionID = Convert.ToString(dr["ProductVersionID"]);
            function.SubSystemID = Convert.ToString(dr["ProductSubSystemID"]);
            return function;
        }
    }
}
